package com.xkdx.guangguang.module.statics;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.xkdx.guangguang.pushserviceforSelf.PushForSelfInfo;
import com.xkdx.guangguang.shareclass.ProductInfo;

public class IConstants {


	public static String INFO_URL = "http://gginter.guangguang.net.cn/PaymentApi/index.php/Index/indexAll";
//	public static String INFO_URL = "http://118.244.208.7/ggapi_new/PaymentApi/index.php/Index/indexAll";

    public static String USR_URL = "http://cpinternew.guangguang.net.cn/Api/Index/indexAll";
//    public static String USR_URL = "http://118.244.208.7/cpapi_new/Api/Index/indexAll";

	//正式地址之前
	public static String addressV2 = "http://gginter.guangguang.net.cn/InterfaceV2.php";
//	public static String addressV2 = "http://118.244.208.7/ggapi_new/InterfaceV2.php";
	//正式地址之后

	// 测试地址
	public static String TEST_ADD = "http://172.16.24.33/gg_api/PaymentApi/index.php/Index/indexAll";

    public static String LOGIN_URL = "http://cpinternew.guangguang.net.cn/Api/Index/indexAll";
//	public static String LOGIN_URL = "http://118.244.208.7/cpapi_new/Api/Index/indexAll";
	// 新浪微博的登录账号
	public static String CONSUMER_KEY = "1210317754"; // 新浪微博登录key值
	public static String REDIRECT_URL = "http://www.guangguang.net.cn"; // 新浪微博跳转路径
	// qq登录账号
	public static String APP_ID = "100411852";
	/**
	 * 1普通登陆，2新浪微博登陆,3腾讯登陆,4绑定新浪微博,5绑定qq登陆,6评论的新浪微博绑定,7快速注册
	 */
	public static int LoginWhich = 1;
	public static boolean IsDisEnable = false;

	// home附近接口
	public static String homeV2 = "http://172.16.24.33/gg_api/InterfaceV2.php";
    public static String key = "@#$%^&*(Adhgf)*duq81mdisoa^&$@$F";


	public static int BottomBtnSelected = 3;
	public static String SP_CITY = "city_db";
	public static String SP_BRAND = "brand_db";
	public static String SP_USER = "user";
	public static String SP_VERSION = "version";
	public static String SP_WEIBO = "blog";
	public static String SP_GUIDE = "guide";
	public static String SP_UPDATEVERSIONTIP = "version_tip";
	public static String SP_SERVERNUM = "selfservice";
	public static String SP_POS = "pos";

	public static String Shop_CommentNum = "0"; // 更新商场详情页面评论数
	public static String Brand_CommentNum = "0"; // 更新品牌详情页面评论总数
	public static boolean isCommitSuccess = false;
    public static boolean isLocationSuccess = false;
    public static boolean isChoiceCity = false;
	public static String SP_USER_NEW = "userNew";

	// 是否有定制推送消息
	public static boolean isHasPush = false;
	public static boolean isFromPush = false;
	public static boolean isFromSelf =false;
	 public static PushForSelfInfo selfInfo = null;
	 public static boolean isHasSelfPush =false;
	 

	// 屏幕宽高
	public static int DisplayWidth = 0;
	public static int DisplayHeight = 0;
	// 位置和经纬度
	public static String currentPosition;
	public static double lat = 0;
	public static double lon = 0;
	// 跳转方向
	public static String objectType = "1";
	// 跳转参数
	public static String objectValue = "1";

	// 是否在刷新界面
	public static boolean isRefresh = false;

	public static boolean isBrandPhotoComment = false; // 判断对相片的评论
	public static boolean isUpLoadBrandPhoto = false;
	public static boolean isBranchUpLoadPhtoto = false;
	public static boolean isShopUpLoadPhoto = false;
	public static boolean isShopPhotoComment = false;
	public static boolean isFromBranchFocuse = false;
	public static boolean isFromShopFocuse = false;
	public static boolean isFromInfo = false;
	public static HashMap<String, String> singlePhotoComment = new HashMap<String, String>();

	// 百度地图校验值
	public static double latCheck = 0.006004;
	public static double lonCheck = 0.006783;

	public static String POS_ADDRESS = "";
	public static int POS_PORT = 8888;

	public static String POS_SHOPID = "";
	public static String POS_FROMWHERE = "";

	public static ProductInfo ProductStatic = new ProductInfo();

	/*
	 * 给图片地址末尾添加字符串
	 */
	public static String addSuffix(String imageUrl, String imageSuffix) {
		if (imageUrl != "") {
			int i = imageUrl.lastIndexOf('.');
			char[] a = imageUrl.toCharArray();
			StringBuffer url = new StringBuffer();
			for (int j = 0; j < a.length; j++) {
				url.append(a[j]);
			}
			if (i != -1) {
				return url.insert(i, imageSuffix).toString();

			} else {
				return url.toString();
			}
		} else {
			return "";
		}
	}

	/**
	 * 判断存储卡是否存在
	 * 
	 * @return
	 */
	public static boolean existSDcard() {
		if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
				.getExternalStorageState())) {
			return true;
		} else
			return false;
	}

	// 输入法隐藏
	public static void hideInputMethodAways(Context context, View view) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}

	public static void showInputMethod(Context context, View view) {
		InputMethodManager im = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		im.showSoftInput(view, 0);
	}

	// 设置listView的高度
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
		listView.setLayoutParams(params);
	}

	public static int getListViewHeight(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return 0;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		return params.height;
	}

	public static String getCurrentTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date(System.currentTimeMillis());
		return format.format(date);
	}

	public static String getPhotoTime() {
		return "2100-1-1 06:11:11";
	}

	public static String getCommentTime() {
		return "2100-1-1";
	}

	// 计算图片的inSampleSize
	public static int computeSampleSize(BitmapFactory.Options options,

	int minSideLength, int maxNumOfPixels) {

		int initialSize = computeInitialSampleSize(options, minSideLength,

		maxNumOfPixels);

		int roundedSize;

		if (initialSize <= 8) {

			roundedSize = 1;

			while (roundedSize < initialSize) {

				roundedSize <<= 1;

			}

		} else {

			roundedSize = (initialSize + 7) / 8 * 8;

		}

		return roundedSize;

	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,

	int minSideLength, int maxNumOfPixels) {

		double w = options.outWidth;

		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 :

		(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));

		int upperBound = (minSideLength == -1) ? 128 :

		(int) Math.min(Math.floor(w / minSideLength),

		Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {

			// return the larger one when there is no overlapping zone.

			return lowerBound;

		}

		if ((maxNumOfPixels == -1) &&

		(minSideLength == -1)) {

			return 1;

		} else if (minSideLength == -1) {

			return lowerBound;

		} else {
			return upperBound;

		}

	}

	// 将View变为Bitmap
	public static Bitmap getBitmapFromView(View view) {
		view.destroyDrawingCache();
		view.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
		view.setDrawingCacheEnabled(true);
		Bitmap bitmap = view.getDrawingCache(true);
		return bitmap;
	}

	public static void download(Context context, String clientDownloadUrl) {
		try {

			PackageManager packageMgr = context.getPackageManager();

			List<PackageInfo> list = packageMgr.getInstalledPackages(0);
			for (int i = 0; i < list.size(); i++) {
				PackageInfo info = list.get(i);
				String temp = info.packageName;
				if (temp.equals("com.uc.browser")) {
					showUCBrowser(context, clientDownloadUrl);
					break;
				} else if (temp.equals("com.tencent.mtt")) {
					showQQBrowser(context, clientDownloadUrl);
					break;
				} else if (temp.equals("com.opera.mini.android")) {
					showOperaBrowser(context, clientDownloadUrl);
					break;
				} else if (temp.equals("com.android.browser")) {
					showGoogleBrower(context, clientDownloadUrl);
					break;
				}
			}
		} catch (Exception e) {
			Toast.makeText(context, "请先下载安装QQ、欧朋或UC浏览器...", Toast.LENGTH_LONG)
					.show();
		}
	}

	public static void showGoogleBrower(Context context, String url) {
		Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		it.setClassName("com.android.browser",
				"com.android.browser.BrowserActivity");
		context.startActivity(it);
	}

	public static void showUCBrowser(Context context, String url) {
		Intent intent = new Intent();
		intent.setClassName("com.uc.browser", "com.uc.browser.ActivityUpdate");
		intent.setAction(Intent.ACTION_VIEW);
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		intent.setData(Uri.parse(url));
		context.startActivity(intent);
	}

	public static void showQQBrowser(Context context, String url) {
		Intent intent = new Intent();
		intent.setClassName("com.tencent.mtt", "com.tencent.mtt.MainActivity");
		intent.setAction(Intent.ACTION_VIEW);
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		intent.setData(Uri.parse(url));
		context.startActivity(intent);
	}

	public static void showOperaBrowser(Context context, String url) {
		Intent intent = new Intent();
		intent.setClassName("com.opera.mini.android",
				"com.opera.mini.android.Browser");
		intent.setAction(Intent.ACTION_VIEW);
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		intent.setData(Uri.parse(url));
		context.startActivity(intent);
	}

	public static int getScreenWidth(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getWidth();
	}

	public static int getScreenHeight(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getHeight();
	}

	// 字符串转成16进制形式的字符串
	public static String toHexString(String s) {
		String str = "";
		for (int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			str = str + s4;
		}
		return str;// 0x表示十六进制
	}

	/**
	 * Convert hex string to byte[]
	 * 
	 * @param hexString
	 *            the hex string
	 * @return byte[]
	 */
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	/**
	 * Convert char to byte
	 * 
	 * @param c
	 *            char
	 * @return byte
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	private static String hexString = "0123456789ABCDEF";

	public static String UnicodeToHexGBK(String str) {
		// 根据默认编码获取字节数组
		byte[] bytes = str.getBytes();
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		// 将字节数组中每个字节拆解成2位16进制整数
		for (int i = 0; i < bytes.length; i++) {
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}

	public static int ConutHanZi(String str) {

		int count = 0;
		Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]");
		Matcher m = p.matcher(str);
		while (m.find()) {
			count++;
		}
		return count;
	}
	
	/** 
     * ByteBuffer 转换 String 
     * @param buffer 
     * @return 
     */  
    public static String getString(ByteBuffer buffer)  
    {  
        Charset charset = null;  
        CharsetDecoder decoder = null;  
        CharBuffer charBuffer = null;  
        try  
        {  
            charset = Charset.forName("GBK");  
            decoder = charset.newDecoder();  
            // charBuffer = decoder.decode(buffer);//用这个的话，只能输出来一次结果，第二次显示为空  
            charBuffer = decoder.decode(buffer.asReadOnlyBuffer());  
            return charBuffer.toString();  
        }  
        catch (Exception ex)  
        {  
            ex.printStackTrace();  
            return "";  
        }  
    }  
    
    public static  String TentoSixteen(int queryLength) {
		if (queryLength > 0) {
			String result = Integer.toHexString(queryLength);
			int len = result.length();
			StringBuffer sb = null;

			while (len < 4) {
				sb = new StringBuffer();
				sb.append("0").append(result);// 左(前)补0
				result = sb.toString();
				len = result.length();
			}

			return result;
		} else {
			return "0000";
		}

	}


}
